<?php

namespace App\Http\Controllers;

use App\Http\Resources\ExamineResource;
use App\Laravue\Models\examineFlow;
use App\Laravue\Models\examineRecord;
use App\Laravue\Models\examineStep;
use App\Laravue\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;


class ExamineController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        return ExamineResource::collection(examineFlow::all());
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Laravue\Models\examineFlow  $examineFlow
     * @return \Illuminate\Http\Response
     */
    public function show(examineFlow $examineFlow)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Laravue\Models\examineFlow  $examineFlow
     * @return \Illuminate\Http\Response
     */
    public function edit(examineFlow $examineFlow)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Laravue\Models\examineFlow  $examineFlow
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, examineFlow $examineFlow)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Laravue\Models\examineFlow  $examineFlow
     * @return \Illuminate\Http\Response
     */
    public function destroy(examineFlow $examineFlow)
    {
        //
    }

    public function examineSetStep(Request $request){
        $id=$request->input('flow_id');
        //先删除
        examineStep::where('flow_id',$id)->delete();
        $step=$request->input('step');

        foreach ($step as $key=>$value)
        {
            if($value['index'] != $key+1){
                throw new Exception('数据不匹配');
            }
            $ids="";
            if(isset($value['user_id'])){
                $ids=implode(",",$value['user_id']);
            }
            examineStep::updateOrCreate(
                ['flow_id'=>$id,'order_id'=>$value['index']],
                ['status'=>$value['status'],'user_id'=>$ids]
            );

        }


       return new ExamineResource(['code'=>200]);
    }

    public function getStepByFolwId($id,Request $request){
        $examinStep=examineStep::where("flow_id",$id)->get();
        $step=[];
        foreach ($examinStep as $index=>$val){
            $step[$index]['index']=$index+1;
            $step[$index]['status']=$val['status'];
            if($val['user_id']!='') {
                $user_ids = explode(',', $val['user_id']);
                if (count($user_ids) > 0) {
                    $temp=[];
                    foreach ($user_ids as $v) {
                        $temp[] = (int)$v;
                    }
                    $step[$index]['user_id'] = $temp;

                }
            }
            if($val['status']=='1'){
                $step[$index]['show']=false;
            }else
            {
                $step[$index]['show']=true;
            }
        }
        return new ExamineResource($step);
    }


    //根据 type 返回全部审核流程
    public function getExamineAll(){
        $list = examineFlow::where('status','1')
            ->withCount('step')
            ->get();
        return new ExamineResource($list);
    }


    public function getUserLeads($user_id){
        $submit_user_info=User::find($user_id);
        $roleName = $submit_user_info->getRoleNames();
        $leadUsers = User::where([['is_lead','1'],['is_delete','0']])->role($roleName[0])->get()->toArray();

        return $leadUsers;
    }

    //根据审核流id 返回 层级和应该审核人
    public function getUsersByFolwId($id,$submit_user,Request $request){
        $examinStep=examineStep::where("flow_id",$id)->get();
        $leadUsers=$this->getUserLeads($submit_user);
        $leadUsers = Arr::pluck($leadUsers,'name');
        $users=User::where('is_delete',0)->pluck('name','id')->toArray();
        $step=[];
        foreach ($examinStep as $index=>$val){
            $step[$index]['index']=$index+1;
            $step[$index]['status']=$val['status'];
            //如果是指定用户
            if($val['user_id']!='') {
                $user_ids = explode(',', $val['user_id']);
                if (count($user_ids) > 0) {
                    foreach ($user_ids as $v) {
                        $temp[] = (int)$v;
                    }
                    $step[$index]['user_id'] = $temp;
                    $step[$index]['user_name'] =Arr::only($users,$temp);
                }
            }else{
                //获取用户角色
                $step[$index]['user_name'] = $leadUsers;
            }

        }
        return new ExamineResource($step);
    }


    //审核操作
    //$review_type 1 通过 2拒绝
    public function review(Request $request){
        $id=$request->input('id');
        $flow_id=$request->input('flow_id');
        $order_id=$request->input('order_id');
        $review_type=$request->input('review_type');
        $note=$request->input('note');

        //审批流
        $examineFlow=examineFlow::where('id',$flow_id)->withCount('step')->first();
        //具体审批步骤
        $examineStep=examineStep::where([['flow_id',$flow_id],['order_id',$order_id]])->first();
        //获取数据详情
        $info=$this->getInfoByTypeAndId($examineFlow->types,$id);
        //判断是否有审核权限
        if($examineStep->status=='1')
        {
            $leads=$this->getUserLeads($info->submituser);
            $review_user=Arr::pluck($leads,'id','id');
        }elseif($examineStep->status=='2')
        {
             $user_assign= explode(',', $examineStep['user_id']);
             foreach ($user_assign as $value)
             {
                 $review_user[$value]=$value;
             }
            //$review_user=User::where('is_delete',0)->pluck('name','id')->toArray();
        }

        if(!isset($review_user[Auth::id()])){
            throw new \Exception('您没权限审核!');
        }
        //执行事务
        DB::beginTransaction();
        try{
            //获取正确的审核状态
            $check_status=$this->setExadminStatus($order_id,$examineFlow->step_count,$review_type);
            //修改当前详情 并 生成记录
            $this->updateExamine($examineFlow->types,$id,$order_id,$check_status,$note,$review_type);
            DB::commit();
        }catch (Exception $exception){

            DB::rollBack();
        }

        return new ExamineResource(['code'=>200,'msg'=>'审核成功']);


    }

    //审核状态 当前第几审核  总审核层数 审核状态1 通过 2 拒绝
    function setExadminStatus($order_id,$count,$review_type){
        //返回状态 0待审核、1审核中、2审核通过、3审核未通过
        $status=0;
        if($order_id==$count)
        {
            if($review_type==1)
            {
                $status=2;
            }elseif($review_type==2)
            {
                $status=3;
            }
        }elseif ($order_id<$count)
        {
            if($review_type==1)
            {
                $status=1;
            }elseif($review_type==2)
            {
                $status=3;
            }
        }
        return $status;
    }

    //修改详情审核内容
    public function updateExamine($type,$id,$order_id,$check_status,$note,$review_type)
    {
        $table=$this->examine_type_to_table($type);
        //查询是否重复审核
        $info=DB::table($table)->find($id);
        $check_=examineRecord::where([['type',$type],['flow_id',$info->flow_id],['order_id',$order_id],['type_id',$id]])->count();
        if($check_>0)
        {
            throw new \Exception('请勿重复审核！');
        }


        //记录审核记录
        $this->review_record($info->flow_id,$type,$id,$order_id,$note,$review_type);

        if($check_status==1)
        {
            $order_id+=1;
        }
        DB::table($table)
            ->where('id',$id)
            ->update(['order_id'=>$order_id,'check_status'=>$check_status,'flow_user_id'=>Auth::id()]);

    }

    //根据type 详情id 获取表数据
    public function getInfoByTypeAndId($type,$id){
        $table=$this->examine_type_to_table($type);
        $one=DB::table($table)->find($id);
        return $one;
    }

    //根据type 返回 表
    public function examine_type_to_table($type){
        $table='';
        switch ($type){
            //合同
            case 'contract':
                $table='contracts';
                break;
            //充值
            case 'renew':
                $table='money_records';
                break;
            //退款
            case 'refund':
                $table='money_records';
                break;
            //回款
            case 'backMoney':
                $table='pay_back';
                break;
            //发票
            case 'invoice':
                $table='invoices';
                break;
            //媒体合同
            case 'media_contract':
                $table='contracts';
                break;
            //转款
            case 'transfer':
                $table='money_records';
                break;
        }
        if($table=='')
        {
            throw new \Exception('获取不到表');
        }
        return $table;
    }

    //审核记录
    public function review_record($flow_id,$type,$type_id,$order_id,$note,$review_type){
        $model= new examineRecord();
        $model->flow_id=$flow_id;
        $model->type=$type;
        $model->type_id=$type_id;
        $model->order_id=$order_id;
        $model->check_user_id=Auth::id();
        $model->check_time=Date('Y-m-d H:i:s');
        $model->content=$note;
        $model->status=$review_type;
        return $model->save();
    }

    //获取审核记录
    public function get_review_record($flow_id,$id){
        //审批流
        $examineFlow=examineFlow::where('id',$flow_id)->withCount('step')->first();
        $list=examineRecord::with('user')
            ->where([['flow_id',$flow_id],['type',$examineFlow->types],['type_id',$id]])
            ->orderBy('order_id','asc')
            ->get();

        return ExamineResource::collection($list);
    }
}
